package com.itheima.dao.impl;

import com.itheima.dao.UserDao;
import com.itheima.domain.User;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

/**
 * @author ZhangyiA
 * @describe:
 * @date 2021/06/27
 */

@Repository("userDao")
public class UserDaoImpl implements UserDao {

    @Resource(name = "jdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    public List<User> findAll() {
        String sql = "select * from sys_user";
        List<User> userList = jdbcTemplate.query(sql , new BeanPropertyRowMapper<User>(User.class));
        return userList;
    }

    @SuppressWarnings("Duplicates")
    public long save(final User user) {
        // 创建 PreparedStatementCreator
        PreparedStatementCreator creator = new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                // 使用原始的 jdbc 完成一个 PrepareStatement的组件
                PreparedStatement preparedStatement = connection.prepareStatement("insert into sys_user values(?,?,?,?,?)" , PreparedStatement.RETURN_GENERATED_KEYS);
                preparedStatement.setObject(1 , null);
                preparedStatement.setString(2 , user.getUsername());
                preparedStatement.setString(3 , user.getEmail());
                preparedStatement.setString(4 , user.getPassword());
                preparedStatement.setString(5 , user.getPhoneNum());
                return preparedStatement;
            }
        };
        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(creator , keyHolder);
        // 通过 keyHolder 获取的主键
        long userId = keyHolder.getKey().longValue();
        return userId; // 返回当前保存数据的 id ，是数据库生成的
    }

    public void saveUserRole(long id, long[] roleIds) {
        String sql = "insert into sys_user_role values(?,?)" ;
        for(long roleId : roleIds){
            jdbcTemplate.update(sql , id , roleId);
        }
    }

    public void del(long userId) {
        String sql = "delete from sys_user where id = ?";
        jdbcTemplate.update(sql , userId);

    }

    public void delUserRole(long userId) {
        String sql = "delete from sys_user_role where userId = ? ";
        jdbcTemplate.update(sql , userId);
    }

}
